<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
require('@/echarts/customed') // echarts theme

const animationDuration = 2000

export default {
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '350px',
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      },
    },
  },
  mounted() {
    this.$bus.$on('onresize', this.onResize)
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    this.$bus.$off('onresize', this.onResize)
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  activated() {
    this.onResize()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'customed')
      this.setOptions(this.chartData)
      this.chart.on('click', (param) => {
        this.$emit('click', param)
      })
    },
    setOptions({ xAxis, series, legend } = {}) {
      if (!this.chart || !xAxis || !series) {
        return
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          padding: [5, 10],
        },
        legend: {
          data: legend,
        },
        grid: {
          left: 20,
          right: 40,
          bottom: 20,
          containLabel: true,
        },
        xAxis: {
          data: xAxis,
          boundaryGap: false,
          axisTick: {
            show: false,
          },
          axisLabel: {
            interval: 0,
            // rotate: xAxis && xAxis.length > 10 ? 60 : 0,
            rotate: 60,
          },
        },
        yAxis: {
          type: 'value',
          // 整条y轴
          axisLine: {
            show: true,
          },
          axisTick: {
            show: false,
          },
        },
        series: series.map((item) => {
          return {
            name: item.name,
            type: 'line',
            smooth: true,
            data: item.data,
            animationDuration,
            animationEasing: 'cubicInOut',
          }
        }),
      }

      this.chart.setOption(option, true)
    },
    onResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
  },
}
</script>
